/*
Autor: Alexander Savochkin, 2010
New BSD License
*/

#include "IoServiceSource.h"
#include "Config.h"
#include "TCPServer.h"
#include "Manager.h"
#include "LogDefinitions.h"

#include <exception>
#include <iostream>

#include <boost/log/common.hpp>
#include <boost/log/formatters.hpp>
#include <boost/log/filters.hpp>

#include <boost/log/utility/init/to_file.hpp>
#include <boost/log/utility/init/to_console.hpp>
#include <boost/log/utility/init/common_attributes.hpp>

using namespace SRCLF;

const char* control_loop_config_filename = "demo.config";

void initializeLoggers(std::string filename, severity_level file_level_threshold, severity_level console_level_threshold)
{
	namespace formatters = boost::log::formatters;
	namespace keywords = boost::log::keywords;
	namespace filters = boost::log::filters;

	// The first thing we have to do to get using the library is
	// to set up the logging sinks - i.e. where the logs will be written to.
	boost::log::init_log_to_console(std::clog, keywords::format = "%TimeStamp%: %_%");

	// One can also use lambda expressions to setup filters and formatters
	boost::log::init_log_to_file
	(
		"sample.log",
		keywords::filter = filters::attr< severity_level >("Severity", std::nothrow) >= notification,
		keywords::format = formatters::format("%1% [%2%] <%3%> %4%")
		% formatters::date_time("TimeStamp", std::nothrow)
		% formatters::time_duration("Uptime", std::nothrow)
		% formatters::attr< severity_level >("Severity", std::nothrow)
		% formatters::message()
	);

	// Also let's add some commonly used attributes, like timestamp and record counter.
	boost::log::add_common_attributes();
}

int main(int argc,char *argv[])
{
	initializeLoggers("control_loop.log", normal, normal);
	boost::log::sources::severity_logger< severity_level > logger;
	try {
		//Read configuration
		SRCLF::Config::Configuration config;
		config.readConfigFile( control_loop_config_filename );
		config.processInheritace();

		//Initailize manager
		boost::asio::io_service& io_service = SRCLF::getCommonIOService();
		SRCLF::Manager manager;
		manager.init(config);

		//Initialize server
		//TODO: Used servers type should be defined by config
		SRCLF::Server::TCPServer control_loop_server(io_service, manager, config);
		
		//Start time and events tracking
		io_service.run();
	}
	catch( std::exception &e ) {
		BOOST_LOG_SEV(logger, critical) << "Exception caught in function 'main': " << e.what();
	}
	catch(...) {
		BOOST_LOG_SEV(logger, critical) << "Unknown exception caught in function 'main': ";
	}
	return 0;
}
